package com.cunyme;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.http.util.ByteArrayBuffer;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class Blackboard_content_page extends Activity
{
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
		SQLiteDatabase cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        helper_functions helpers = new helper_functions();
		Map <String, String> blackboard_cookies = helpers.getcookies("blackboard", cuny_meDB);
		cuny_meDB.close();
        // In this page, we are creating a layout of buttons based on the user's class schedule.  Because this is dynamic,
        // we create the layout here, as opposed to in an xml file.
        
        // This creates the main layout...
    	ScrollView content_layout = new ScrollView(this);
    	content_layout.setBackgroundColor(0xffffffff);
    	LinearLayout child_layout = new LinearLayout(this); 
    	/*announcements_layout.setLayoutParams(new LayoutParams(
	            LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
;*/
    	child_layout.setOrientation(LinearLayout.VERTICAL);
    	child_layout.setBackgroundColor(0xffffffff);
    	LinearLayout.LayoutParams bboard_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
    			LinearLayout.LayoutParams.WRAP_CONTENT); 
		content_layout.addView(child_layout);
		
		// content_id=_5094898_1
		Connection content_conn;
		if (getIntent().getExtras().getString("is_ann").equals("no"))
			content_conn = Jsoup.connect("https://bbhosted.cuny.edu/webapps/blackboard/content/listContent.jsp").data("course_id", getIntent().getExtras().getString("course_id"), "content_id", getIntent().getExtras().getString("content_id")).cookie("JSESSIONID", blackboard_cookies.get("JSESSIONID")).cookie("session_id", blackboard_cookies.get("session_id")).cookie("ObSSOCookie", blackboard_cookies.get("ObSSOCookie")).cookie("NSC_100211.qspe2_wjq2:443", blackboard_cookies.get("NSC_100211.qspe2_wjq2:443")).cookie("BIGipServerbbhosted_ssl_pl", blackboard_cookies.get("BIGipServerbbhosted_ssl_pl"));
		else
			content_conn = Jsoup.connect("https://bbhosted.cuny.edu/webapps/blackboard/content/launchLink.jsp").data("ann_id", getIntent().getExtras().getString("ann_id"), "course_id", getIntent().getExtras().getString("course_id")).cookie("JSESSIONID", blackboard_cookies.get("JSESSIONID")).cookie("session_id", blackboard_cookies.get("session_id")).cookie("ObSSOCookie", blackboard_cookies.get("ObSSOCookie")).cookie("NSC_100211.qspe2_wjq2:443", blackboard_cookies.get("NSC_100211.qspe2_wjq2:443")).cookie("BIGipServerbbhosted_ssl_pl", blackboard_cookies.get("BIGipServerbbhosted_ssl_pl"));
		try
		{
			org.jsoup.nodes.Document content_doc = content_conn.timeout(10*1000).post();
			String content_html = content_doc.html();
			String[] content_str_manip = content_html.split("<!-- End TitleBar-->");
			String[] content_beg_elements = content_str_manip[0].split("<!-- Start TitleBar-->");
			content_beg_elements[1] = content_beg_elements[1].replaceAll("<.*?>", "");
			content_beg_elements[1] = content_beg_elements[1].trim();
			content_beg_elements[1] = content_beg_elements[1] + '\n';
			TextView main_title = new TextView(this);
			main_title.setText(content_beg_elements[1]);
			main_title.setId(999);
			main_title.setTypeface(Typeface.DEFAULT_BOLD);
			main_title.setTextSize(16);
			main_title.setLayoutParams(bboard_params);
			main_title.setTextColor(0xff000000);
			child_layout.addView(main_title);
			
			String[] content_elements = content_str_manip[1].split("</tr>");
			for (int i = 0; i < content_elements.length - 1; i++)
			{
				content_elements[i] = content_elements[i].replaceFirst("</span>", "<b>cockadoodledoo");
				final String[] two_content_parts = content_elements[i].split("<b>cockadoodledoo");
	
				two_content_parts[0] = two_content_parts[0].replaceAll("<a", "gobblegobblegobblezzz");
				two_content_parts[0] = two_content_parts[0].replaceAll("</a", "commacommacommazzz");
				two_content_parts[0] = two_content_parts[0].replaceAll("<.*?>", "");
				two_content_parts[0] = two_content_parts[0].replaceAll("gobblegobblegobblezzz", "<a");
				two_content_parts[0] = two_content_parts[0].replaceAll("commacommacommazzz", "</a");
				
				
				TextView content_title = new TextView(this);
				
				String title_link_name = two_content_parts[0].replaceAll("<.*?>", "").trim();
				
				if (two_content_parts[0].indexOf("content_id") >= 0)
				{
					SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
					stringBuilder.append(title_link_name);
					stringBuilder.setSpan(
							new ClickableSpan() {
								@Override
								public void onClick(View widget)
								{
									String[] string_manip = two_content_parts[0].split("content_id=");
									string_manip = string_manip[1].split("\"");	
									String content_id = string_manip[0].trim();
									Intent gotoContentPage = new Intent(Blackboard_content_page.this, Blackboard_content_page.class);
									gotoContentPage.putExtra("course_id", getIntent().getExtras().getString("course_id"));
									gotoContentPage.putExtra("content_id", content_id);
									gotoContentPage.putExtra("is_ann", "no");
									startActivity(gotoContentPage);
								}
							},
							0, title_link_name.length(),
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					content_title.setText(stringBuilder);
				}
				else
					content_title.setText(Html.fromHtml(two_content_parts[0].trim()));
				
				content_title.setId(i);
				content_title.setTypeface(Typeface.DEFAULT_BOLD);
				content_title.setMovementMethod(LinkMovementMethod.getInstance());
				content_title.setLayoutParams(bboard_params);
				content_title.setTextColor(0xff000000);
				child_layout.addView(content_title);
				
				
				two_content_parts[1] = two_content_parts[1].replaceAll("<a", "gobblegobblegobblezzz");
				two_content_parts[1] = two_content_parts[1].replaceAll("</a", "commacommacommazzz");
				two_content_parts[1] = two_content_parts[1].replaceAll("</p>", "<br /><br />");
				two_content_parts[1] = two_content_parts[1].replaceAll("<br />", "kookookoozzz");
				two_content_parts[1] = two_content_parts[1].replace("<!--[if gte mso", "onetwobucklemyshoe");
				two_content_parts[1] = two_content_parts[1].replace("<![endif]-->", "threefourclosethedoor");
				two_content_parts[1] = two_content_parts[1].replaceAll("<.*?>", "");
				two_content_parts[1] = two_content_parts[1].replace("onetwobucklemyshoe", "<!--[if gte mso");
				two_content_parts[1] = two_content_parts[1].replace("threefourclosethedoor", "<![endif]-->");
				two_content_parts[1] = two_content_parts[1].replaceAll("kookookoozzz", "<br />");
				two_content_parts[1] = two_content_parts[1].replaceAll("gobblegobblegobblezzz", "<a");
				two_content_parts[1] = two_content_parts[1].replaceAll("commacommacommazzz", "</a");
				two_content_parts[1] = two_content_parts[1] + "<br />";
				
				final String[] content_part_components = two_content_parts[1].split("<a hr");
				
				//Toast.makeText(getApplicationContext(), two_content_parts[1], Toast.LENGTH_LONG).show();	
				//Toast.makeText(getApplicationContext(), "begin content chunk", Toast.LENGTH_LONG).show();	

				for (int j = 0; j < content_part_components.length; j++)
				{
					TextView content_content = new TextView(this);
					child_layout.addView(content_content);
					//Toast.makeText(getApplicationContext(), content_part_components[j], Toast.LENGTH_LONG).show();	
					if (content_part_components[j].indexOf("ef=") >= 0)
					{
						content_part_components[j] = "<a hr" + content_part_components[j];
						if (content_part_components[j].indexOf("@@") >= 0)
						{
							final String content_component = content_part_components[j];
							String[] pre_post_link = content_component.split("</a>");
							String link_name = pre_post_link[0].replaceAll("<.*?>", "");
							SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
							stringBuilder.append(link_name);
							stringBuilder.setSpan(
									new ClickableSpan()
									{
										@Override
										public void onClick(View widget)
										{
											String[] string_manip = content_component.split("ef=");
											string_manip = string_manip[1].split("\">");
											final String url_string = string_manip[0].replace("\"", "");
											
											final String[] url_components = url_string.split("/");
											File downloadedFile = new File(Environment.getExternalStorageDirectory() + "/blackboard/" + url_components[url_components.length - 4] + "/" + url_components[url_components.length - 1]);
									        
											AlertDialog.Builder builder = new AlertDialog.Builder(Blackboard_content_page.this);
											builder.setMessage(url_components[url_components.length - 1] + " already exists. Overwrite?")
											       .setCancelable(false)
											       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
															Intent download_file = new Intent(Blackboard_content_page.this, Download_helper.class);
															download_file.putExtra("url", url_string);
															download_file.putExtra("fileName", url_components[url_components.length - 1]);
															startActivity(download_file);
											           }
											       })
											       .setNegativeButton("No", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
											                dialog.cancel();
											           }
											       });
											AlertDialog alert = builder.create();
											
											if(downloadedFile.exists())
												alert.show();
											else
											{
												Intent download_file = new Intent(Blackboard_content_page.this, Download_helper.class);
												download_file.putExtra("url", url_string);
												download_file.putExtra("fileName", url_components[url_components.length - 1]);
												startActivity(download_file);
											}
										}
									},
									0, link_name.length(),
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							content_content.setText(stringBuilder);
							
							TextView left_over = new TextView(this);
							left_over.setText(Html.fromHtml(pre_post_link[1]));
							left_over.setMovementMethod(LinkMovementMethod.getInstance());
							left_over.setId(i + 500);
							left_over.setLayoutParams(bboard_params);
							left_over.setTextColor(0xff000000);
							child_layout.addView(left_over);
						}
						else if (content_part_components[j].indexOf("do_assignment") >= 0)
						{
							final String content_component = content_part_components[j];
							String[] pre_post_link = content_component.split("</a>");
							content_content.setText(Html.fromHtml("<i>This page contains a link to a Blackboard Assignment.  " +
									"This application does not handle Blackboard Assignments.  To access this assignment," +
									"you must use a web browser.</i><br /><br />"));
							
							TextView left_over = new TextView(this);
							left_over.setText(Html.fromHtml(pre_post_link[1]));
							left_over.setMovementMethod(LinkMovementMethod.getInstance());
							left_over.setId(i + 500);
							left_over.setLayoutParams(bboard_params);
							left_over.setTextColor(0xff000000);
							child_layout.addView(left_over);	
						}
						else if (content_part_components[j].indexOf("content_id") >= 0)
						{
							final String content_component = content_part_components[j];
							String[] pre_post_link = content_component.split("</a>");
							String link_name = pre_post_link[0].replaceAll("<.*?>", "");
							SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
							stringBuilder.append(link_name);
							stringBuilder.setSpan(
									new ClickableSpan() {
										@Override
										public void onClick(View widget)
										{
											String[] string_manip = two_content_parts[1].split("content_id=");
											string_manip = string_manip[1].split("\"");	
											String content_id = string_manip[0].trim();
											Intent gotoContentPage = new Intent(Blackboard_content_page.this, Blackboard_content_page.class);
											gotoContentPage.putExtra("course_id", getIntent().getExtras().getString("course_id"));
											gotoContentPage.putExtra("content_id", content_id);
											startActivity(gotoContentPage);
										}
									},
									0, link_name.length(),
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							content_content.setText(stringBuilder);
							
							TextView left_over = new TextView(this);
							left_over.setText(Html.fromHtml(pre_post_link[1]));
							left_over.setMovementMethod(LinkMovementMethod.getInstance());
							left_over.setId(i + 500);
							left_over.setLayoutParams(bboard_params);
							left_over.setTextColor(0xff000000);
							child_layout.addView(left_over);	
						}
						else
							content_content.setText(Html.fromHtml(content_part_components[j]));
					}
					else
						content_content.setText(Html.fromHtml(content_part_components[j]));
					content_content.setMovementMethod(LinkMovementMethod.getInstance());
					content_content.setId(i + 500);
					content_content.setLayoutParams(bboard_params);
					content_content.setTextColor(0xff000000);

				}
			}
			
		    setContentView(content_layout);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Unable to Establish Connection.  Please try again.", Toast.LENGTH_SHORT).show();	
			finish();
		}
    }

}
